package com.atguigu.datastream.day04;

import com.atguigu.datastream.bean.Event;
import com.mysql.jdbc.Driver;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * ClassName: Flink_03_Sink_Mysql
 * Package: com.atguigu.day04
 * Description:
 *
 * @Author ChenJun
 * @Create 2023/4/10 18:20
 * @Version 1.0
 */
public class Flink_03_Sink_Mysql {
    public static void main(String[] args) throws Exception {

        //1. 创建流是执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2. 读取数据
        DataStreamSource<Event> streamSource = env.fromElements(new Event("junjun", "./home", 1000L),
                new Event("liangliang", "./cart", 2000L)
        );

        SinkFunction<Event> sink = JdbcSink.sink("insert into clicks values(?,?)",
                new JdbcStatementBuilder<Event>() {
                    @Override
                    public void accept(PreparedStatement preparedStatement, Event event) throws SQLException {
                        preparedStatement.setString(1, event.user);
                        preparedStatement.setString(2, event.url);
                    }
                },
                new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                        .withUrl("jdbc:mysql://hadoop102:3306/test")
                        .withUsername("root")
                        .withPassword("000000")
                        .withDriverName(Driver.class.getName())
                        .build()
        );

        streamSource.addSink(sink);
        env.execute();
    }
}
